#ifndef __LOG_HPP__
#define __LOG_HPP__

#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <ctime>
#include <memory>
#include "Mutex.hpp"

namespace LogModule
{
    using namespace MutexMouble;
    const std::string gsep = "\r\n";
    // 刷新策略: 显示器, 指定文件
    class LogStrategy
    {
    public:
        ~LogStrategy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };

    //显示器打印策略
    class ConsoleStrategy : public LogStrategy
    {
    public:
        ConsoleStrategy() {}

        void SyncLog(const std::string &message) override
        {
            LockGuard lockguard(_mutex);
            std::cout << message << gsep;
        }

        ~ConsoleStrategy() {}
    private:
        Mutex _mutex;
    };

    //文件打印策略
    const std::string defaultpath = "/var/log";
    const std::string defaultfile = "my.log";
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string path = defaultpath, const std::string file = defaultfile)
            :_path(path), _file(file)
        {
            LockGuard lockguard(_mutex);
            if(std::filesystem::exists(_path)) return;// 检查路径是否存在
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch(const std::filesystem::filesystem_error& e)
            {
                std::cerr << e.what() << '\n';
            }
            
        }

        void SyncLog(const std::string &message) override
        {
            LockGuard lockguard(_mutex);
            std::string filename = _path + (_path.back() == '/' ? "":"/") + _file;
            std::ofstream out(filename, std::ios::app);
            if(!out.is_open()) return;
            out << message << gsep;
            out.close();
        }

        ~FileLogStrategy() {}
    private:
        std::string _path;
        std::string _file;

        Mutex _mutex;
    };

    //形成一条完整日志,选择不同刷新方式

    //日志等级
    enum class LogLevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    std::string LevelStr(LogLevel level)
    {
        switch(level)
        {
            case LogLevel::DEBUG:
                return "DEBUG";
            case LogLevel::INFO:
                return "INFO";
            case LogLevel::WARNING:
                return "WARNING";
            case LogLevel::ERROR:
                return "ERROR";
            case LogLevel::FATAL:
                return "FATAL";
            default:
                return "UNKNOWN";
        }
    }

    //获取时间
    std::string GetTimeStamp()
    {
        time_t curr = time(nullptr);
        struct tm curr_tm;
        localtime_r(&curr, &curr_tm);
        char time[128];
        snprintf(time, sizeof(time), "%04d-%02d-%02d %02d:%02d:%02d", 
                            curr_tm.tm_year+1900,
                            curr_tm.tm_mon+1,
                            curr_tm.tm_mday,
                            curr_tm.tm_hour,
                            curr_tm.tm_min,
                            curr_tm.tm_sec);
        return time;
    }

    class Logger
    {
    public:
        Logger()
        {
            EnableConsoleLogStrategy();
        }

        void EnableFileLogStrategy()
        {
            _fflush_strategy = std::make_unique<FileLogStrategy>();
        }

        void EnableConsoleLogStrategy()
        {
            _fflush_strategy = std::make_unique<ConsoleStrategy>();
        }

        //一条日志
        class LogMessage
        {
        public:
            LogMessage(LogLevel &level, std::string &srcname, int line_number, Logger &logger)
                :_curr_time(GetTimeStamp()),
                 _level(level),
                 _pid(getpid()),
                 _srcname(srcname),
                 _line_number(line_number),
                 _logger(logger)
            {
                std::stringstream ss;
                ss << "[" << _curr_time << "] "
                   << "[" << LevelStr(_level) << "] " 
                   << "[" << _pid << "] "
                   << "[" << _srcname << "] "
                   << "[" << _line_number << "] "
                   << "- ";
                _loginfo = ss.str();
            }

            template<class T>
            LogMessage &operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }

            ~LogMessage()
            {
                if(_logger._fflush_strategy)
                {
                    _logger._fflush_strategy->SyncLog(_loginfo);
                }
            }
        private:
            std::string _curr_time;
            LogLevel _level;
            pid_t _pid;
            std::string _srcname;
            int _line_number; 
            std::string _loginfo; // 完整信息
            Logger &_logger;
        };

        //返回临时对象
        LogMessage operator()(LogLevel leve, std::string srcname, int line_number)
        {
            // 这里编译器会进行优化不会导致发生拷贝构造而导致多余的刷新, 而且c++17起这种优化强制生效
            return LogMessage(leve, srcname, line_number, *this);
        }


        ~Logger(){}
    private:
        std::unique_ptr<LogStrategy> _fflush_strategy;
    };

    //全局日志对象
    Logger logger;

    //使用宏,简化用户操作,获取文件名和行号
    #define LOG(level) logger(level, __FILE__, __LINE__)
    #define Enable_Console_Log_Strategy() logger.EnableConsoleLogStrategy()
    #define Enable_File_Log_Strategy() logger.EnableFileLogStrategy()

} 

#endif